<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Cms\Controller;

use Admin\Controller\AdminActionController;
use Admin\Data\Common;
use Cms\Entity\SingleCms;
use Cms\Form\SingleCmsForm;
use Cms\Service\SingleCmsManager;
use Doctrine\ORM\EntityManager;
use Laminas\Filter\StaticFilter;
use Laminas\Mvc\I18n\Translator;
use Laminas\View\Model\ViewModel;

class CmsSingleController extends AdminActionController
{
    private $translator;
    private $entityManager;
    private $singleCmsManager;

    public function __construct(
        Translator $translator,
        EntityManager $entityManager,
        SingleCmsManager $singleCmsManager
    )
    {
        $this->translator       = $translator;
        $this->entityManager    = $entityManager;
        $this->singleCmsManager = $singleCmsManager;
    }

    /**
     * 单页文章列表
     * @return array|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        //$singleCmsList = $this->entityManager->getRepository(SingleCms::class)->findBy([], ['singleCmsSort' => 'ASC', 'singleCmsId' => 'DESC']);
        $singleCmsList = $this->entityManager->getRepository(SingleCms::class)->findSingleCmsList();

        return ['singleCmsList' => $singleCmsList];
    }

    /**
     * 添加单页文章
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addAction()
    {
        $form = new SingleCmsForm();
        $form->get('singleTag')->setValueOptions($this->shopPlugin()->shopSingleCmsTagOptions($this->translator->translate('不选择标签')));

        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();

                if(!empty($data['singleTag'])) {
                    $singleTagArray = explode('-', $data['singleTag']);
                    if(!in_array($singleTagArray[0], ['pc', 'mobile'])) {
                        $this->flashMessenger()->addWarningMessage($this->translator->translate('该标记的类型不存在!'));
                        return $this->redirect()->toRoute('cms-single');
                    }
                    $templateCode = Common::getDefaultTemplateCode($singleTagArray[0].'Template');

                    $data['singleTag']      = $singleTagArray[1];
                    $data['templateCode']   = $templateCode;
                }

                $this->singleCmsManager->addSingleCms($data);

                $this->adminCommon()->addOperLog(sprintf($this->translator->translate('单页文章 %s 添加成功!'), $data['singleCmsTitle']), $this->translator->translate('单页文章管理'));

                return $this->redirect()->toRoute('cms-single');
            }
        }

        return ['form' => $form];
    }

    /**
     * 编辑单页文章
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editAction()
    {
        $singleCmsId    = (int) $this->params()->fromRoute('id', -1);
        $singleCmsInfo  = $this->entityManager->getRepository(SingleCms::class)->findOneBySingleCmsId($singleCmsId);
        if($singleCmsInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该单页文章不存在!'));
            return $this->redirect()->toRoute('cms-single');
        }

        $form = new SingleCmsForm();
        $form->get('singleTag')->setValueOptions($this->shopPlugin()->shopSingleCmsTagOptions($this->translator->translate('不选择标签')));

        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();

                if(!empty($data['singleTag'])) {
                    $singleTagArray = explode('-', $data['singleTag']);
                    if(!in_array($singleTagArray[0], ['pc', 'mobile'])) {
                        $this->flashMessenger()->addWarningMessage($this->translator->translate('该标记的类型不存在!'));
                        return $this->redirect()->toRoute('cms-single');
                    }
                    $templateCode = Common::getDefaultTemplateCode($singleTagArray[0].'Template');

                    $data['singleTag']      = $singleTagArray[1];
                    $data['templateCode']   = $templateCode;
                }

                $this->singleCmsManager->editSingleCms($data, $singleCmsInfo);

                $this->adminCommon()->addOperLog(sprintf($this->translator->translate('单页文章 %s 编辑成功!'), $data['singleCmsTitle']), $this->translator->translate('单页文章管理'));

                return $this->redirect()->toRoute('cms-single');
            }
        } else {
            $form->setData($singleCmsInfo->valuesArray());
            if(!empty($singleCmsInfo->getTemplateCode())) {
                $templateCodeArray = explode('-', $singleCmsInfo->getTemplateCode());
                $form->setData(['singleTag' => $templateCodeArray[0] . '-' . $singleCmsInfo->getSingleTag()]);
            }
        }

        return ['form' => $form, 'singleCmsInfo' => $singleCmsInfo];
    }

    /**
     * 删除单页文章
     * @return \Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteAction()
    {
        if(!$this->adminCommon()->validatorCsrf()) return $this->adminCommon()->toReferer();

        $singleCmsId    = (int) $this->params()->fromRoute('id', -1);
        $singleCmsInfo  = $this->entityManager->getRepository(SingleCms::class)->findOneBySingleCmsId($singleCmsId);
        if($singleCmsInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该单页文章不存在!'));
            return $this->redirect()->toRoute('cms-single');
        }

        $imageArray = $this->singleCmsManager->deleteSingleCms($singleCmsInfo);

        $this->getEventManager()->trigger('cms-single.delete.post', $this, ['imageArray' => $imageArray]);

        $this->adminCommon()->addOperLog(sprintf($this->translator->translate('单页文章 %s 删除成功!'), $singleCmsInfo->getSingleCmsTitle()), $this->translator->translate('单页文章管理'));

        return $this->adminCommon()->toReferer();
    }

    public function ajaxCmsSearchAction()
    {
        $view = new ViewModel();
        $view->setTerminal(true);

        $page = (int) $this->params()->fromQuery('page', 1);

        $search = [];
        $searchCmsTitle = trim($this->params()->fromQuery('searchCmsTitle'));
        if(!empty($searchCmsTitle)) {
            $searchCmsTitle = StaticFilter::execute($searchCmsTitle, 'StripTags');
            $searchCmsTitle = StaticFilter::execute($searchCmsTitle, 'HtmlEntities');
            $search['single_cms_title'] = $searchCmsTitle;
        }

        $query = $this->entityManager->getRepository(SingleCms::class)->findAllSingleCms($search);
        $cmsList = $this->adminCommon()->shopPaginator($query, $page, 10);

        return $view->setVariables(['cmsList' => $cmsList, 'searchCmsTitle' => $searchCmsTitle]);
    }
}